import axios from "axios";
import router from "../router/index.js";

const newAxios = new axios.create({
    baseURL: "http://47.98.128.191:3000",
    timeout: 5000,
});

// 设置axios请求拦截器
newAxios.interceptors.request.use((config) => {
    const token = localStorage.token;
    config.headers.Authorization = token;
    return config;
}, (err) => {
    return err
})

// 设置axios响应拦截器
newAxios.interceptors.response.use(
    (res) => {
        return res.data
    }, //响应成功
    (err) => {
        console.log(err);
        if (err && err.response && err.response.status) {
            switch (err.response.status) {
                case 401:
                    alert('未登录，请先登录');
                    router.push('/login');
                    break;
                case 404:
                    err.message = "资源找不到，404";
                    break;
                case 500:
                    err.message = "服务器错误，500";
                    break;
                default:
                    err.message = "服务器错误，500";
                    break;
            }
        } else {
            err.message = "服务器错误";
            return Promise.reject(err.message);
        }
    }//响应失败
);

export default newAxios;